<template>
  <section class="log-section">
    <div class="section-header">
      <h2 class="section-title">
        <span class="title-icon">📝</span>
        操作日志
      </h2>
      <div class="section-actions">
        <!-- 日志统计 -->
        <div class="log-stats">
          <div class="stats-item" v-for="(count, type) in logStats" :key="type">
            <span class="stats-icon">{{ getLogTypeIcon(type) }}</span>
            <span class="stats-count">{{ count }}</span>
          </div>
        </div>
        
        <div class="action-buttons">
          <!-- 筛选下拉 -->
          <select 
            v-model="filterType" 
            class="filter-select"
            @change="handleFilterChange"
          >
            <option value="all">全部日志</option>
            <option value="info">信息</option>
            <option value="success">成功</option>
            <option value="warning">警告</option>
            <option value="error">错误</option>
          </select>
          
          <!-- 清空按钮 -->
          <button 
            class="clear-btn"
            @click="handleClearLogs"
            :disabled="!logs.length"
          >
            <span class="clear-icon">🗑️</span>
            清空
          </button>
        </div>
      </div>
    </div>

    <!-- 日志内容区域 -->
    <div class="log-content">
      <div class="log-container" ref="logContainer">
        <!-- 空状态 -->
        <div v-if="!filteredLogs.length" class="empty-state">
          <div class="empty-icon">📝</div>
          <div class="empty-text">暂无操作记录</div>
          <div class="empty-hint">
            {{ logs.length ? '当前筛选条件下无匹配日志' : '开始操作后将显示日志记录' }}
          </div>
        </div>

        <!-- 日志列表 -->
        <transition-group 
          v-else
          name="log-item" 
          tag="div" 
          class="log-list"
        >
          <div
            v-for="log in filteredLogs"
            :key="log.id"
            class="log-item"
            :class="`log-${log.type}`"
            @click="handleLogClick(log)"
          >
            <div class="log-header">
              <div class="log-meta">
                <span class="log-icon">{{ getLogTypeIcon(log.type) }}</span>
                <span class="log-time">{{ log.time }}</span>
                <span class="log-type-badge" :class="`type-${log.type}`">
                  {{ getLogTypeText(log.type) }}
                </span>
              </div>
              <button 
                class="log-remove"
                @click.stop="handleRemoveLog(log.id)"
                title="删除此日志"
              >
                ×
              </button>
            </div>
            
            <div class="log-message">{{ log.message }}</div>
            
            <!-- 详细信息（如果有的话） -->
            <div v-if="log.details" class="log-details">
              <details>
                <summary class="details-summary">查看详情</summary>
                <pre class="details-content">{{ formatDetails(log.details) }}</pre>
              </details>
            </div>
          </div>
        </transition-group>
      </div>
    </div>

    <!-- 日志工具栏 -->
    <div class="log-toolbar">
      <div class="toolbar-left">
        <span class="log-count">
          显示 {{ filteredLogs.length }} / {{ logs.length }} 条日志
        </span>
      </div>
      <div class="toolbar-right">
        <button 
          class="tool-btn"
          @click="scrollToTop"
          :disabled="!filteredLogs.length"
          title="滚动到顶部"
        >
          ⬆️ 顶部
        </button>
        <button 
          class="tool-btn"
          @click="scrollToBottom"
          :disabled="!filteredLogs.length"
          title="滚动到底部"
        >
          ⬇️ 底部
        </button>
        <button 
          class="tool-btn"
          @click="exportLogs"
          :disabled="!logs.length"
          title="导出日志"
        >
          📥 导出
        </button>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, toRefs } from 'vue'
import type { OperationLog } from '../types/app'

// Props
interface Props {
  logs: OperationLog[]
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'clear-logs': []
}>()

// 解构 props
const { logs } = toRefs(props)

// 响应式数据
const logContainer = ref<HTMLElement>()
const filterType = ref<'all' | OperationLog['type']>('all')

// 计算属性
const filteredLogs = computed(() => {
  if (filterType.value === 'all') {
    return logs.value
  }
  return logs.value.filter(log => log.type === filterType.value)
})

const logStats = computed(() => {
  const stats = {
    info: 0,
    success: 0,
    warning: 0,
    error: 0
  }
  
  logs.value.forEach(log => {
    stats[log.type]++
  })
  
  return stats
})

// 方法
const handleFilterChange = (): void => {
  nextTick(() => {
    scrollToTop()
  })
}

const handleClearLogs = (): void => {
  if (confirm('确定要清空所有日志吗？')) {
    emit('clear-logs')
  }
}

const handleLogClick = (log: OperationLog): void => {
  console.log('日志点击:', log)
}

const handleRemoveLog = (logId: string): void => {
  // 这里可以发送事件给父组件来删除特定日志
  console.log('删除日志:', logId)
}

const getLogTypeIcon = (type: OperationLog['type']): string => {
  const iconMap = {
    info: 'ℹ️',
    success: '✅',
    warning: '⚠️',
    error: '❌'
  }
  return iconMap[type] || '📝'
}

const getLogTypeText = (type: OperationLog['type']): string => {
  const typeMap = {
    info: '信息',
    success: '成功',
    warning: '警告',
    error: '错误'
  }
  return typeMap[type] || '未知'
}

const formatDetails = (details: any): string => {
  try {
    return typeof details === 'object' 
      ? JSON.stringify(details, null, 2)
      : String(details)
  } catch {
    return String(details)
  }
}

const scrollToTop = (): void => {
  logContainer.value?.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

const scrollToBottom = (): void => {
  logContainer.value?.scrollTo({
    top: logContainer.value.scrollHeight,
    behavior: 'smooth'
  })
}

const exportLogs = (): void => {
  const logData = logs.value.map(log => ({
    时间: log.time,
    类型: getLogTypeText(log.type),
    消息: log.message,
    详情: log.details
  }))

  const dataStr = JSON.stringify(logData, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  
  const link = document.createElement('a')
  link.href = url
  link.download = `operation-logs-${new Date().toISOString().slice(0, 19)}.json`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  URL.revokeObjectURL(url)
}
</script>

<style scoped>
.log-section {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid #e9ecef;
  margin-bottom: 24px;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 32px;
  border-bottom: 2px solid #f1f3f5;
  background: #f8f9fa;
  flex-wrap: wrap;
  gap: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 1.4rem;
  font-weight: 700;
  color: #2c3e50;
}

.title-icon {
  font-size: 1.5rem;
}

.section-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.log-stats {
  display: flex;
  gap: 8px;
}

.stats-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: #f3f4f6;
  border-radius: 12px;
  font-size: 0.8rem;
}

.stats-icon {
  font-size: 0.9rem;
}

.stats-count {
  font-weight: 600;
  color: #374151;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.filter-select {
  padding: 6px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 0.85rem;
  background: white;
  cursor: pointer;
}

.clear-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: #fee2e2;
  color: #991b1b;
  border: 1px solid #fca5a5;
  border-radius: 6px;
  font-size: 0.85rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.clear-btn:hover:not(:disabled) {
  background: #fecaca;
  border-color: #f87171;
}

.clear-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.clear-icon {
  font-size: 0.9rem;
}

/* 日志内容区域 */
.log-content {
  padding: 20px 32px;
}

.log-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #fafbfc;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #9ca3af;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 12px;
  opacity: 0.6;
}

.empty-text {
  font-size: 1.1rem;
  font-weight: 500;
  margin-bottom: 6px;
  color: #6b7280;
}

.empty-hint {
  font-size: 0.9rem;
}

/* 日志项样式 */
.log-list {
  padding: 8px;
}

.log-item {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-left: 4px solid transparent;
}

.log-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateX(2px);
}

.log-item:last-child {
  margin-bottom: 0;
}

/* 日志类型样式 */
.log-info {
  border-left-color: #3b82f6;
}

.log-success {
  border-left-color: #10b981;
}

.log-warning {
  border-left-color: #f59e0b;
}

.log-error {
  border-left-color: #ef4444;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.log-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.log-icon {
  font-size: 1rem;
}

.log-time {
  font-size: 0.8rem;
  color: #6b7280;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.log-type-badge {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 0.7rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.type-info {
  background: #dbeafe;
  color: #1e40af;
}

.type-success {
  background: #d1fae5;
  color: #065f46;
}

.type-warning {
  background: #fef3c7;
  color: #92400e;
}

.type-error {
  background: #fee2e2;
  color: #991b1b;
}

.log-remove {
  background: none;
  border: none;
  color: #9ca3af;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 4px;
  line-height: 1;
}

.log-remove:hover {
  background: #f3f4f6;
  color: #6b7280;
}

.log-message {
  color: #374151;
  font-size: 0.9rem;
  line-height: 1.4;
  margin-bottom: 6px;
}

.log-details {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f3f4f6;
}

.details-summary {
  font-size: 0.8rem;
  color: #6b7280;
  cursor: pointer;
  margin-bottom: 6px;
}

.details-content {
  background: #1e293b;
  color: #e2e8f0;
  padding: 8px;
  border-radius: 4px;
  font-size: 0.75rem;
  line-height: 1.4;
  margin: 0;
  overflow-x: auto;
}

/* 日志工具栏 */
.log-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 32px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
  font-size: 0.85rem;
}

.log-count {
  color: #6b7280;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.tool-btn {
  padding: 4px 8px;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.8rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.tool-btn:hover:not(:disabled) {
  background: #f9fafb;
  border-color: #9ca3af;
}

.tool-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 动画效果 */
.log-item-enter-active {
  transition: all 0.3s ease;
}

.log-item-leave-active {
  transition: all 0.3s ease;
}

.log-item-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.log-item-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

.log-item-move {
  transition: transform 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .section-actions {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .log-content {
    padding: 16px 20px;
  }
  
  .log-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .log-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .log-remove {
    align-self: flex-end;
  }
}
</style>
